package cn.hairui.blog.controller;

import cn.hairui.blog.configure.WebLog;
import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.entity.Artical;
import cn.hairui.blog.entity.Link;
import cn.hairui.blog.entity.Myinfo;
import cn.hairui.blog.service.*;
import cn.hairui.blog.util.BlogUtil;
import cn.hairui.blog.util.DateUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 友情链接表 前端控制器
 * </p>
 *
 * @author laoganbu
 * @since 2020-04-12
 */
@Controller
public class LinkController {

    @Autowired
    private MyinfoService myinfoService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;
    @Autowired
    private ArticalService articalService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private VisitrecordService visitrecordService;

    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    //// ==========================前台==============================///////
    @RequestMapping(value = "/link", method = RequestMethod.GET)
    @WebLog(description = "友情链接")
    public String link(Model model) {
        // 我的信息
        Myinfo myinfo = myinfoService.getById(PubConstant.MY_INFO_ID);
        model.addAttribute("myinfo", myinfo);

        // 分类信息
        List<Map> typesList = typeService.selectByShowFlag(PubConstant.YES_NO_Y, PubConstant.INDEX_TOP_TYPE_COUNT);
        model.addAttribute("types", typesList);

        // 标签信息
        List<Map> tagList = tagService.selectTags(PubConstant.INDEX_TOP_TAG_COUNT, PubConstant.YES_NO_Y);
        model.addAttribute("tags", tagList);

        // 最新推荐
        List<Artical> newList = articalService.listTop(PubConstant.INDEX_TOP_NEWARTICAL_COUNT, "create_time");
        model.addAttribute("newarticals", newList);

        // 本站信息
        int artical_count = articalService.count();// 文章总数
        int type_count = typeService.count();// 分类总数
        int tag_count = tagService.count();// 标签总数
        int comment_count = messageService.count();
        int visit_count = visitrecordService.count();
        int today_visit_count = visitrecordService.countByDate(DateUtil.getCurrentDate());

        Map webinfo = new HashMap();
        webinfo.put("artical_count", artical_count);
        webinfo.put("type_count", type_count);
        webinfo.put("tag_count", tag_count);
        webinfo.put("comment_count", comment_count);
        webinfo.put("visit_count", visit_count);
        webinfo.put("today_visit_count", today_visit_count);
        model.addAttribute("webinfo", webinfo);

        // 好友博客
        Map t1 = new HashMap();
        t1.put("type", PubConstant.BOLG_TYPE_1);
        List<Link> links_t1 = (List<Link>) linkService.listByMap(t1);

        // 大佬博客
        Map t2 = new HashMap();
        t2.put("type", PubConstant.BOLG_TYPE_2);
        List<Link> links_t2 = (List<Link>) linkService.listByMap(t2);

        // 学习网站
        Map t3 = new HashMap();
        t3.put("type", PubConstant.BOLG_TYPE_3);
        List<Link> links_t3 = (List<Link>) linkService.listByMap(t3);

        model.addAttribute("links_t1", links_t1);
        model.addAttribute("links_t2", links_t2);
        model.addAttribute("links_t3", links_t3);

        return "link";
    }

    //// ==========================后台==============================///////
    // 列表页面
    @RequestMapping(value = "/manage/link/list", method = RequestMethod.GET)
    public String list() {
        return "page/link/list";
    }

    // 新增页面
    @RequestMapping(value = "/manage/link/add")
    public String add() {
        return "page/link/add";
    }

    // 列表数据
    @RequestMapping(value = "/manage/link/data")
    @ResponseBody
    public String data(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int pageSize = 10;// 默认每页显示5条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> linkList = linkService.list();

        PageInfo<Map> pageInfo = new PageInfo<Map>(linkList);
        map.put("data", linkList);
        map.put("code", 0);
        map.put("count", pageInfo.getTotal());
        return JSONUtils.toJSONString(map);
    }

    // 修改展示标志
    @RequestMapping(value = "/manage/link/status")
    @ResponseBody
    @Transactional
    public String status(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int id = Integer.parseInt(request.getParameter("id"));
        String status = request.getParameter("status");
        Link link = new Link();
        link.setId(id);
        link.setStatus(status);
        linkService.saveOrUpdate(link);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    // 删除数据
    @RequestMapping(value = "/manage/link/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String delete(@Param(value = "id") int id, HttpServletRequest request) {
        Map map = new HashMap();
        // 删除文件
        Link link = linkService.getById(id);
        String path = uploadPath + PubConstant.LINK_DIR + link.getWebicon();
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        linkService.removeById(id);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    // 新增数据
    @RequestMapping(value = "/manage/link/addData")
    @ResponseBody
    public String addData(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        String fileName = "";
        File targetPath = new File(uploadPath + PubConstant.LINK_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }
        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    fileName = file.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    // 重新生成文件名
                    fileName = BlogUtil.getUUIDUpperCase() + suffixName;
                    String path = uploadPath + PubConstant.LINK_DIR + fileName;
                    // 上传
                    try {
                        file.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String webname = request.getParameter("webname");
        String webmaster = request.getParameter("webmaster");
        //String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String url = request.getParameter("url");
        String type = request.getParameter("type");
        String motto = request.getParameter("motto");

        Link link = new Link();
        link.setWebname(webname);
        link.setUrl(url);
        link.setWebmaster(webmaster);
        //link.setPhone(phone);
        link.setEmail(email);
        link.setType(type);
        link.setMotto(motto);
        link.setCreatetime(DateUtil.getCurrentTime());
        link.setWebicon(fileName);
        link.setStatus(PubConstant.APPROVE_STS_1);
        linkService.saveOrUpdate(link);

        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }
}
